/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dinner.web;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @version 2
 * @author Bizon
 */
public class Eat implements Externalizable {

	private static final long serialVersionUID = 6607227329773105401L;
	private double price;
	private int pieces;
	private String name;

	public Eat() {
	}

	public Eat(double price, int pieces, String name) {
		this.price = price;
		this.pieces = pieces;
		this.name = name;
	}

	public Eat(String line) {
		parceLine(line);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Eat) {
			Eat e = (Eat) obj;
			return e.name.equals(name) && e.pieces == pieces && e.price == price && e.getClass().equals(Eat.class);
		}
		return super.equals(obj);
	}

	public String getName() {
		return name;
	}

	public int getPieces() {
		return pieces;
	}

	public double getPrice() {
		return price;
	}

	@Override
	public int hashCode() {
		return name.hashCode() ^ pieces ^ (int) price;
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		String line = in.readUTF();
		parceLine(line);
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setPieces(int pieces) {
		this.pieces = pieces;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Eat [name=" + name + ", pieces=" + pieces + ", price=" + price + "]";
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeUTF(name + "\t" + price + "\t" + pieces);
	}

	private void parceLine(String line) {
		String[] elems = line.split("\t");
		if (elems.length > 0) {
			name = elems[0];
			try {
				if (elems.length > 1) {
					price = Double.parseDouble(elems[1]);
					if (elems.length > 2) {
						pieces = Integer.parseInt(elems[2]);
					}
				}
			} catch (NumberFormatException e) {
				Logger.getLogger(Eat.class.getName()).log(Level.SEVERE, e.getMessage(), e);
			}
		}
	}
}
